package camid.services.nodemanager;

import camid.distribution.interceptor.InvocationInterceptor;
import camid.distribution.protocol.MethodRequestMessage;
import camid.distribution.protocol.MethodResponseMessage;

public class ForwarderInvokerInterceptor implements InvocationInterceptor {

	private NodeManager nm;
	
	public ForwarderInvokerInterceptor(NodeManager nm) {
		this.nm = nm;
	}

	@Override
	public void beforeInvocation(MethodRequestMessage requestMessage)
			throws Exception 
	{
		String objectId = requestMessage.getDescriptor().getObjectId();
		while( objectMoved(objectId, ObjectStatus.MOVING) )
		{
			try 
			{
				Thread.sleep(100);
			}
			catch(InterruptedException e)
			{
				e.printStackTrace();
			}
		}
		if( objectMoved(objectId, ObjectStatus.MOVED) )
		{
			throw new ForwardingException( requestMessage.getDescriptor(), 
					ObjectStatus.MOVED);
		}
	}

	private boolean objectMoved(String objectId, ObjectStatus expectedStatus) {
		ObjectStatus status = nm.getObjectStatus(objectId);
		if(status != null && status.equals(expectedStatus))
		{
			return true;
		}
		return false;
	}

	@Override
	public void afterInvocation(MethodResponseMessage responseMessage)
			throws Exception {
		// TODO Auto-generated method stub

	}

}
